package com.wdl.datarest.implementation;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.ibm.icu.text.SimpleDateFormat;
import com.wdl.datarest.data.DeviceRepository;
import com.wdl.datarest.data.Person;
import com.wdl.datarest.data.PersonRepository;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerHandler extends ChannelInboundHandlerAdapter {

	private DevCnfgCache devCnfgCache;

	private PersonRepository personRepo;

	private InfluxDBData influxDBData;

	private DeviceRepository deviceRepo;

	private ShouHuanDataCache shouHuanDataCache;

	public ServerHandler(DevCnfgCache _devCache, PersonRepository _personRepo, InfluxDBData _influxDBData,
			DeviceRepository _deviceRepo, ShouHuanDataCache shDc) {
		this.devCnfgCache = _devCache;
		this.personRepo = _personRepo;
		this.influxDBData = _influxDBData;
		this.deviceRepo = _deviceRepo;
		this.shouHuanDataCache = shDc;
	}

	/**
	 * 客户端与服务端创建连接的时候调用
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// System.out.println("客户端与服务端连接开始...");
	}

	/**
	 * 客户端与服务端断开连接时调用
	 */
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// System.out.println("客户端与服务端连接关闭...");

		String sessionId = NettyConfig.getSessionId(ctx.channel());

		NettyConfig.remove(sessionId);
	}

	/**
	 * 服务端接收客户端发送过来的数据结束之后调用
	 */
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
		// System.out.println("信息接收完毕...");
	}

	/**
	 * 工程出现异常的时候调用
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	/**
	 * 这里接收了客户端发来的信息
	 */
	@Override
	public void channelRead(ChannelHandlerContext channelHandlerContext, Object info) throws Exception {
		ByteBuf buf = (ByteBuf) info;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req, "UTF-8");
		System.out.println("****接收客户端数据*****:" + body + "----" + new Date().toString());
		try {
			if (!body.startsWith("@B#@")) {
				return;
			}

			String[] bodyArr = body.split("\\|");

			String devId2 = "20CH" + bodyArr[3];
			System.out.println("设备id:" + devId2);
			CacheData cacheData = devCnfgCache.getCnfgDataFromCacheByDeviceIdString(devId2);
			if (cacheData == null) {
				System.out.println("设备不存在");
				return;
			}

			long longPersonId = cacheData.getPersonId();
			Person person = personRepo.findByIndex(longPersonId);
			if (person == null) {
				System.out.println("用户不存在");
				return;
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String dateStr = sdf.format(new Date());
			// cmd
			String cmd = bodyArr[2];
			if (cmd.equals("003")) {
				ByteBuf pingMessage = Unpooled.buffer();

				String locCmd = "@B#@|01|004|" + bodyArr[3] + "|1|" + dateStr + "|@E#@";

				String config = "@B#@|01|042|" + bodyArr[3]
						+ "|5|5|00000700|09001100|01001800|1|1||10086&\u0031\u0030\u0032|7|45&150||||0|" + dateStr
						+ "|@E#@";
				String pcmd = locCmd + config;
				System.out.println("发送命令：" + pcmd);
				pingMessage.writeBytes(pcmd.getBytes("UTF-8"));
				channelHandlerContext.channel().writeAndFlush(pingMessage);
			} else if (cmd.equals("012")) {
				short heartRate = Short.parseShort(bodyArr[7]);

				shouHuanDataCache.updateHeartRate(String.valueOf(person.getId()), person.getPersonName(), devId2,
						heartRate);
				System.out.println("心率：" + heartRate);

				ByteBuf pingMessage = Unpooled.buffer();

				String locCmd = "@B#@|01|013|" + bodyArr[3] + "|1|" + dateStr + "|@E#@";
				pingMessage.writeBytes(locCmd.getBytes("UTF-8"));
				channelHandlerContext.channel().writeAndFlush(pingMessage);
			} else if (cmd.equals("010")) {
				short hv = Short.parseShort(bodyArr[7]);

				System.out.println("高压：" + hv);

				short lv = Short.parseShort(bodyArr[8]);
				System.out.println("低压：" + lv);
				shouHuanDataCache.updateHlv(String.valueOf(person.getId()), person.getPersonName(), devId2, hv, lv);
				ByteBuf pingMessage = Unpooled.buffer();

				String locCmd = "@B#@|01|011|" + bodyArr[3] + "|1|" + dateStr + "|@E#@";
				pingMessage.writeBytes(locCmd.getBytes("UTF-8"));
				channelHandlerContext.channel().writeAndFlush(pingMessage);
			} else if (cmd.equals("001")) {

				String type = bodyArr[bodyArr.length - 2];

				if (type.equals("1")) {
					String wd = bodyArr[8];
					String jd = bodyArr[9];
					Map<String, String> tags = new HashMap<>();
					Map<String, Object> fields = new HashMap<>();
					tags.put("personid", String.valueOf(person.getId()));
					tags.put("personname", person.getPersonName());
					tags.put("devid", devId2);

					fields.put("longitude", Double.parseDouble(jd));
					fields.put("dimension", Double.parseDouble(wd));
					System.out.println("坐标：" + wd + "," + jd);
					influxDBData.insert("gps_data", tags, fields);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}